package web.action.com;


import com.fz.us.base.bean.Pager;
import com.joint.base.entity.Permission;
import com.joint.base.entity.Users;
import com.joint.base.service.PermissionService;
import com.joint.base.util.DataUtil;
import net.sf.json.JSONObject;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import web.action.BaseFlowAction;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by gcw on 2014/9/29.
 */
public class AjaxCommentAction extends BaseFlowAction {
    @Resource
    private TaskService taskService;
    @Resource
    private RepositoryService repositoryService;
    @Autowired
    protected RuntimeService runtimeService;
    @Resource
    private PermissionService permissionService;

    private ArrayList<Map<String,Object>>  taskArrayList;

    public String key;
    /**
     * 待办视图
     */
    public String toUsersList(){
        Users users = usersService.getLoginInfo();
        List<Task> taskList = taskService.createTaskQuery().taskCandidateOrAssigned(users.getId()).active().orderByTaskCreateTime().desc().list();
        taskArrayList=new ArrayList();
        Map<String,Object> rMap;
        for(Task task : taskList){
            ProcessDefinition processDefinition = workflowService.getProDefinitionByTask(task);
            ProcessInstance processInstance = workflowService.getProIntanceByTask(task);

            if(workflowService.getNumStatus(processInstance.getBusinessKey(),users) == 0){
                continue;
            }

            rMap = new HashMap<String,Object>();
            rMap.put("pname",processDefinition.getName()==null?repositoryService.createDeploymentQuery().deploymentId(processDefinition.getDeploymentId()).singleResult().getName():processDefinition.getName());
            rMap.put("time",task.getCreateTime());
            String toUser;
            String msg = "";
            HistoricTaskInstance lastTask = workflowService.earlyTask(task.getProcessInstanceId());
            if(lastTask != null){
                toUser = usersService.get(lastTask.getAssignee()).getName();
                List<Comment> comments = taskService.getTaskComments(lastTask.getId());
                for(Comment comment : comments){
                    msg = msg+comment.getFullMessage()+"["+ DataUtil.DateTimeToString(comment.getTime())+"]";
                }
            }else{
                toUser = "";
            }

            rMap.put("toUser",toUser);
            rMap.put("msg",msg);
            rMap.put("docId",processInstance.getBusinessKey());
            Permission permission = permissionService.getByKey(processDefinition.getKey());
            if(permission !=null){
                rMap.put("url",permission.getUrl());
            }else {
                rMap.put("url","");
            }


            if(StringUtils.isEmpty("msg")){
                rMap.put("msg","暂时没有审批意见");
            }
            taskArrayList.add(rMap);
        }
        return  "toUsersList";
    }
    public String draftList(){
        List<Task> taskList = taskService.createTaskQuery().processVariableValueEquals("numStatus",0).taskAssignee(usersService.getLoginInfo().getId()).active().orderByTaskCreateTime().desc().list();
        System.out.println(taskList.size());
        taskArrayList=new ArrayList();
        Map<String,Object> rMap;
        for(Task task : taskList){
            ProcessInstance processInstance = workflowService.getProIntanceByTask(task);
            ProcessDefinition processDefinition = workflowService.getProDefinitionByTask(task);
            rMap = new HashMap<String, Object>();
            rMap.put("time",task.getCreateTime());
            rMap.put("creater",workflowService.getStarter(processInstance.getBusinessKey()));
            rMap.put("pName",processDefinition.getName());
            System.out.print("defId"+processDefinition.getKey());
            System.out.print("docId"+processInstance.getBusinessKey());
            rMap.put("docId",processInstance.getBusinessKey());
            rMap.put("key",processDefinition.getKey());
            Permission permission = permissionService.getByKey(processDefinition.getKey());
            if(permission !=null){
                rMap.put("url",permission.getUrl());
            }else {
                rMap.put("url","");
            }
            taskArrayList.add(rMap);
        }
        return "draftList";
    }

    /**
     * 删除草稿
     * @return
     */
    public String draftDelete(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400","删除失败!","操作状态");
        }
        workflowTraceService.draftDelete(key,keyId);
        return ajaxHtmlCallback("200","删除成功!","操作状态");
    }
    /**
     * 待办和草稿视图
     * @return
     */
    public String todoAndDraft(){
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        List<Task> taskList = taskService.createTaskQuery().taskAssignee(usersService.getLoginInfo().getId()).taskAssignee(usersService.getLoginInfo().getId()).active().orderByTaskCreateTime().desc().list();
        for(Task task : taskList){
            ProcessInstance processInstance = workflowService.getProIntanceByTask(task);
            ProcessDefinition processDefinition = workflowService.getProDefinitionByTask(task);
            List<Map<String,Object>> commentlists=workflowService.getCommentList(processInstance.getProcessInstanceId());
            for(Map<String,Object> map:commentlists){
                Map<String,Object> rMap = new HashMap<String,Object>();
                rMap.putAll(map);
                rMap.put("nextApprover",nextApprover(processInstance.getBusinessKey()));
                rMap.put("processname",processDefinition.getName());
                rMap.put("time",task.getCreateTime());
                rMap.put("docId",processInstance.getBusinessKey());
                dataRows.add(JSONObject.fromObject(rMap));
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 跳转到草稿、待办视图
     * @return
     */
    public String todoAndDraftList(){
        return  "todoAndDraftList";
    }
    public ArrayList<Map<String, Object>> getTaskArrayList() {
        return taskArrayList;
    }

    public void setTaskArrayList(ArrayList<Map<String, Object>> taskArrayList) {
        this.taskArrayList = taskArrayList;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}
